package com.lyk.coursearrange.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyk.coursearrange.common.core.base.code.CodeEnum;
import com.lyk.coursearrange.common.exception.MZException;
import com.lyk.coursearrange.dao.OnlineCategoryDao;
import com.lyk.coursearrange.dao.ScheduleDao;
import com.lyk.coursearrange.dao.ScheduleOrStudentDao;
import com.lyk.coursearrange.dao.TeacherDao;

import com.lyk.coursearrange.entity.Schedule;

import com.lyk.coursearrange.entity.dto.DiagnosisDto;
import com.lyk.coursearrange.entity.dto.OnlineCategoryDto;
import com.lyk.coursearrange.entity.dto.ScheduleDto;
import com.lyk.coursearrange.entity.dto.TeacherDto;
import com.lyk.coursearrange.service.ScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ScheduleServiceImpl extends ServiceImpl<ScheduleDao, Schedule> implements ScheduleService {


    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private OnlineCategoryDao onlineCategoryDao;
    @Autowired
    private ScheduleDao scheduleDao;
    @Autowired
    private ScheduleOrStudentDao scheduleOrStudentDao;

    @Override
    public List<TeacherDto> getteacherlist() {
        return teacherDao.getteacherlist();
    }

    @Override
    public List<OnlineCategoryDto> categorylist() {
        return onlineCategoryDao.getcategorylist();
    }

    @Override
    public List<OnlineCategoryDto> categorytwolist() {
        return onlineCategoryDao.categorytwolist();
    }

    @Override
    public List<Schedule> selectschedule(Map<String,String> param) {
        Long page = null;
        Long limit = null;
        Long offset = null;
        Long teacher_id = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        // 转为calendar格式
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        // 如果是周日
        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            calendar.add(Calendar.DAY_OF_YEAR,-1);
        }

        /**
         * calendar.get(Calendar.MONTH)+1  calendar中的月份以0开头
         * Calendar.DAY_OF_WEEK 当前日期是所在周的第几天（以周日为一周的第一天）
         * Calendar.DATE 当前日期是几号
         *  */

        // 获取当前日期是当周的第i天
        int i = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        // 获取当前日期所在周的第一天
        calendar.add(Calendar.DATE , -i+1);
        String start_time =new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
        // 获取当前日期所在周的最后一天
        calendar.add(Calendar.DATE, 6);
        String end_time =new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());








        if(param.get("teacher_id")!=null&&!param.get("teacher_id").equals("")){
            teacher_id = Long.parseLong(param.get("teacher_id"));
        }
        if(param.get("page")!=null&&!param.get("page").equals("")){
            page = Long.valueOf(param.get("page"));
        }
        if(param.get("limit")!=null&&!param.get("limit").equals("")){
            limit = Long.valueOf(param.get("limit"));

        }
        if(page!=null &&limit!=null){
           offset= (page - 1) * limit;
        }



        if(param.get("start_time")!=null&&!param.get("start_time").equals("")){
            start_time = param.get("start_time");
        }
        if(param.get("end_time")!=null&&!param.get("end_time").equals("")){
            end_time = param.get("end_time");
        }

        System.out.println(teacher_id);
        System.out.println(start_time);
        System.out.println(end_time);
        System.out.println(offset);
        System.out.println(limit);



      List<Schedule> list = scheduleDao.selectschedule(teacher_id,start_time,end_time,offset,limit);
      return list;
    }

    @Override
    @Transactional
    public boolean addschedule(Map<String, String> param) {
        Long course_scheduling_no = Long.valueOf(IdUtil.getSnowflake().nextIdStr());
        System.out.println("雪花算法生成的不重复用户编号:"+course_scheduling_no);
        Schedule schedule = Schedule.builder()
                .courseSchedulingNo(course_scheduling_no)
                .courseId(Long.valueOf(param.get("courseId")))
                .courseDate(param.get("courseDate"))
                .courseTimeOn(param.get("courseTimeOn"))
                .courseEndTime(param.get("courseEndTime"))
                .classId(Long.valueOf(param.get("classId")))
                .teacherId(Long.valueOf(param.get("teacherId")))
                .categoryId(Long.valueOf(param.get("categoryId")))
                .classroom(param.get("classroom"))
                .numberOfClassDeductions(Long.valueOf(param.get("numberOfClassDeductions")))
                .recurrentScheduling(Long.valueOf(param.get("recurrentScheduling")))
                .canMakeAnAppointment(Long.valueOf(param.get("canMakeAnAppointment")))
                .courseNotes(param.get("courseNotes"))
                .build();
        int addschedule= scheduleDao.insert(schedule);
        System.out.println("排课信息添加进去了吗？"+addschedule);
        if(addschedule>0){

          Long schedule_id =   schedule.getScheduleId();
            System.out.println(schedule_id);
            String a = param.get("studentId");
            String[] student_id=a.split(",");
            for (int i = 0; i < student_id.length; i++) {
                System.out.println(student_id[i]);
                if(scheduleOrStudentDao.insertto(schedule_id,Long.valueOf(student_id[i]))){
                    System.out.println("排课和学院关系添加成功!");
                }else {
                    System.out.println("排课和学院关系添加失败!");
                }
            }
            return true;
        }else {
            return true;
        }
    }

    @Override
    public Schedule selectscheduleone(Long schedule_id) {
        return getById(schedule_id);
    }

    @Override
    public boolean updateschedule(Map<String, String> param) {
        Long schedule_id = Long.valueOf(param.get("scheduleId"));
        Schedule schedule = Schedule.builder()
                .courseDate(param.get("courseDate"))
                .courseTimeOn(param.get("courseTimeOn"))
                .courseEndTime(param.get("courseEndTime"))
                .teacherId(Long.valueOf(param.get("teacherId")))
                .build();
        UpdateWrapper<Schedule> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("schedule_id",schedule_id);
        return  update(schedule,updateWrapper);
    }

    @Override
    public boolean signin(Map<String, String> param) {
        Long schedule_id  = Long.valueOf(param.get("scheduleId"));
        String a = param.get("studentId");
        String[] student_id=a.split(",");
        for (int i = 0; i < student_id.length; i++) {
            System.out.println(student_id[i]);
            if(scheduleOrStudentDao.signin(schedule_id,Long.valueOf(student_id[i]))){
                System.out.println("签到成功!");
            }else {
                System.out.println("签到失败!");
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean classending(Map<String, String> param) throws MZException {
        Long schedule_id  = Long.valueOf(param.get("scheduleId"));
        Long class_ending = Long.valueOf(param.get("classEnding"));
        //未签到人数
        Long signpeople = scheduleOrStudentDao.selectsignin(schedule_id);
        if(signpeople>0){
            throw  new MZException(CodeEnum.SignNo);
        }
        UpdateWrapper<Schedule> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("class_ending",class_ending);
        updateWrapper.eq("schedule_id",schedule_id);
        return update(updateWrapper);
    }

    @Override
    public boolean saveStudent(DiagnosisDto dto,Long scheduleId) {
        Long teacherId = dto.getTeacherId();
        Long studentId = dto.getStudentId();
         scheduleOrStudentDao.addTeaAsStu(teacherId,studentId);
        return scheduleOrStudentDao.addStuAsSch(studentId,scheduleId);

    }
}
